package com.cqie.hospitalescort.config.utils;

import com.cqie.hospitalescort.utils.DateUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.*;
import java.util.function.Function;

@Component
public class JwtUtil {

    private static final String secret = "hospitalEscortweiXinAndBackgroundSystemfas";

    public static String getUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    /**
     * 创建token
     */
    public static String createToken(String username, String role, String password) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("role", role);
        //此处的username包括：后台的用户名，微信登录的openid
        claims.put("username", username);
        claims.put("password", password);

        long expiration = 60 * 60 * 1000L * 24;
        return Jwts.builder()
                .setId(getUUID())
                .setClaims(claims)
                .setSubject(username)
                .setIssuedAt(DateUtil.getNowDate())
                .setIssuer("gongDY")
                .setExpiration(new Date(System.currentTimeMillis() + expiration))
                .signWith(SignatureAlgorithm.HS256, generalKey())
                .compact();
    }

    public String extractSubject(String token) {
        return extractClaim(token, Claims::getSubject);
    }

    public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
        Claims claims = extractAllClaims(token);
        return claimsResolver.apply(claims);
    }

    private Claims extractAllClaims(String token) {
        return Jwts.parser()
                .setSigningKey(generalKey())
                .setAllowedClockSkewSeconds(300) // 设置允许的时钟偏差为 5 分钟
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 秘钥转换成HmacSHA256格式
     *
     * @return
     */
    public static SecretKey generalKey() {
        byte[] encodeKey = Base64.getDecoder().decode(JwtUtil.secret);
        return new SecretKeySpec(encodeKey, 0, encodeKey.length, "HmacSHA256");
    }


}

